package com.neu.controller;

import com.neu.base.PageBean;
import com.neu.base.Result;
import com.neu.entity.DTO.NoticeDTO;
import com.neu.entity.Notice;
import com.neu.entity.Task;
import com.neu.entity.security.LoginUser;
import com.neu.service.NoticeService;
import com.neu.utils.excel.ExcelUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/notices")
@Tag(name = "通知管理")
public class NoticeController {

    @Autowired
    NoticeService noticeService;

    @PostMapping("/page")
    @Parameters({
            @Parameter(name = "pageNum", description = "页码", required = true),
            @Parameter(name = "pageSize", description = "每页显示数量", required = true)
    })
    @Operation(summary = "分页查询")
    public Result page(@RequestParam Integer pageNum,
                       @RequestParam Integer pageSize){

        PageBean<NoticeDTO> pagelist = noticeService.pagelist(pageNum, pageSize);
        //如果当前页码值大于总页数，返回最后一页数据
        if (pageNum > pagelist.getTotalPage()) {
            pagelist = noticeService.pagelist((int)pagelist.getTotalPage(), pageSize);
        }
        return Result.success(pagelist);
    }

    @PostMapping("/search")
    @Operation(summary = "搜索通知")
    public Result search(@RequestBody Map map){
        PageBean<NoticeDTO> pagelist = noticeService.search(map);
        return Result.success(pagelist);
    }

    @PostMapping("/publish")
    @Operation(summary = "发布通知")
    public Result publish(@RequestBody NoticeDTO noticeDTO){
        return noticeService.publish(noticeDTO);
    }

    @GetMapping("/export")
    @Operation(summary = "导出通知信息")
    public void export(HttpServletResponse response){
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();
        String fileName ="";
        if (!permissions.contains("ROLE_super")) {
            fileName = loginUser.getTenantName()+"通知信息表.xlsx";// 下载时的文件名
        }else{
            fileName = "swpt所有通知信息表.xlsx";// 下载时的文件名
        }
        String sheetName = "通知信息"; // 工作表名称
        List<Notice> tasks = noticeService.list();
        // 调用工具类进行导出
        ExcelUtil.exportExcel(response, fileName, sheetName, Task.class, tasks);
    }

    @PostMapping("/delete")
    @Operation(summary = "删除通知")
    public Result delete(@RequestBody NoticeDTO noticeDTO){
        return noticeService.delete(noticeDTO);
    }

}
